<template>
    <div class="container-fluid" v-loading="loading">

        <div class="row">
            <div class="col-lg-12">
                <div class="card">

                    <category-menu-component :category-id="categoryId" :active-index="activeIndex"></category-menu-component>

                    <div class="card-toolbar clearfix">
                        <form class="pull-right search-bar" onsubmit="return false;">
                            <div class="input-group-btn">
                                <input type="text" class="form-control" v-model="keyword" placeholder="请输入名称">

                            </div>

                            <div class="input-group-btn">
                                <button class="btn btn-success" type="submit" v-on:click="search()">筛选</button>
                            </div>
                        </form>
                        <div class="toolbar-btn-action">
                            <a class="btn btn-primary m-r-5" href="javascript:void(0)" v-on:click="addAccount()"><i class="mdi mdi-plus"></i>添加公众号</a>
                        </div>
                    </div>

                    <div class="card-body">
                        <div class="table-responsive" style="width: 100%;margin-top: 20px;">
                            <el-table
                                    :data="list"
                                    style="width: 100%"
                                    :default-sort="{prop: 'date', order: 'descending'}"
                            >
                                <el-table-column
                                        label="ID"
                                        type="index"
                                        :index="indexMethod"
                                        width="50">
                                </el-table-column>
                                <el-table-column
                                        prop="name"
                                        label="公众号名称"
                                        width="90">
                                    <template slot-scope="scope">
                                        <a @click="openEdit(scope.row)" style="cursor:pointer;">{{scope.row.name |
                                            titleFormatter}}</a>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="account"
                                        label="微信号"
                                        width="78">
                                </el-table-column>
                                <el-table-column
                                        prop="dayNumber"
                                        label="提取文章数"
                                        width="95">
                                </el-table-column>
                                <el-table-column
                                        prop="todayNumber"
                                        label="今日录入"
                                        width="76">
                                </el-table-column>
                                <el-table-column
                                        prop="yesterdayNumber"
                                        label="昨天录入"
                                        width="76">
                                </el-table-column>
                                <el-table-column
                                        prop="monthNumber"
                                        label="本月录入"
                                        width="76">
                                </el-table-column>
                                <el-table-column
                                        label="状态"
                                        align="center"
                                        width="50">
                                    <template slot-scope="scope">
                                        <p v-if="scope.row.status">是</p>
                                        <p v-else>否</p>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="created_at"
                                        label="加入时间"
                                        width="170"
                                        align="center">
                                </el-table-column>
                                <el-table-column
                                        label="操作"
                                        align="center">
                                    <template slot-scope="scope">
                                        <el-button v-if="scope.row.status" size="mini" @click="setStatus(scope.row._id,0)" type="primary">停用</el-button>
                                        <el-button v-else size="mini" @click="setStatus(scope.row._id,1)" type="success">启用</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <nav style="float: right;">
                                <el-pagination
                                        layout="prev, pager, next, total"
                                        :total="total" :hide-on-single-page="pageActive"
                                        :page-size="pageSize"
                                        :current-page="currentPage"
                                        @current-change="handleCurrentChange"
                                >
                                </el-pagination>
                            </nav>

                            <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
                                <el-form :model="form">

                                    <el-form-item label="公众号名称" :label-width="formLabelWidth">
                                        <el-input
                                                type="text"
                                                placeholder="请输入公众号名称"
                                                v-model="form.name" style="width:80%;">
                                        </el-input>
                                    </el-form-item>

                                    <el-form-item label="微信号" :label-width="formLabelWidth">
                                        <el-input
                                                type="text"
                                                placeholder="请输入微信号"
                                                v-model="form.account" style="width:80%;">
                                        </el-input>
                                    </el-form-item>


                                    <el-form-item label="关联分类" :label-width="formLabelWidth">
                                        <el-autocomplete
                                                v-model="form.categoryName"
                                                :fetch-suggestions="querySearchAsync"
                                                placeholder="请输入内容"
                                                @select="handleFormQuerySelect"
                                                style="width: 100%"
                                        ></el-autocomplete>
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in form.categoryTags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleFormIndustryClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </el-form-item>

                                    <el-form-item label="关联公司" :label-width="formLabelWidth">
                                        <el-autocomplete
                                                v-model="form.companyName"
                                                :fetch-suggestions="queryCompanyAsync"
                                                placeholder="请输入内容"
                                                @select="handleCompanySelect"
                                                style="width: 100%"
                                        ></el-autocomplete>
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in form.companyTags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleCompanyClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </el-form-item>

                                    <el-form-item label="提取当日推送文章数量" :label-width="formLabelWidth">
                                        <el-input
                                                type="number"
                                                placeholder="数量"
                                                v-model="form.dayNumber" style="width:80%;">
                                        </el-input>
                                    </el-form-item>

                                    <el-form-item label="首次提取文章数量" label-width="127px">
                                        <el-input
                                                type="number"
                                                placeholder="数量"
                                                v-model="form.firstNumber" style="width:40%;">
                                        </el-input>
                                        <span style="color:#F56C6C">*提取过一次将为空</span>
                                    </el-form-item>

                                </el-form>
                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                                    <el-button type="primary" @click="submitData(1)">确 定</el-button>
                                </div>
                            </el-dialog>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script>
    import CategoryMenuComponent from "./CategoryMenuComponent";
    export default {
        name: "CategoryOfficialAccountComponent",
        components: {
            "category-menu-component": CategoryMenuComponent,
        },
        data() {
            return {
                keyword: '',
                pageActive: false,
                list: [],
                pageSize: 10,
                total: 0,
                currentPage: 1,
                loading: true,
                activeIndex: '3',
                name: '',
                order: 'desc',
                orderField: '_id',
                form: {
                    name: "",
                    account:"",
                    categoryName: '',
                    categoryIds:[],
                    categoryTags:[],
                    companyIds:[],
                    companyTags:[],
                    companyName:'',
                    dayNumber:0,
                    firstNumber:0,
                    status:1
                },
                //弹窗部分
                formLabelWidth: '120px',
                dialogFormVisible:false,
                status:0,
                categoryId: $('meta[name="id"]').attr('content'),
                companies:[],
                restaurants:[],
                categoryName:'',
                id:'',
                title:'添加公众号'
            }
        },
        methods: {
            search: function () {
                let self = this;
                let uri = 'official-account/post-list';
                self.loading = true;

                let postData = {
                    keyword: self.keyword,
                    page: self.currentPage,
                    order: self.order,
                    orderField: self.orderField,
                    verifyStatus: 1,
                    categoryId: self.categoryId
                };

                axios.post(uri,postData).then(function (result) {
                    self.total = result.officialAccounts.total;
                    if (self.total > 0) {
                        self.pageActive = false;
                    } else {
                        self.pageActive = true;
                    }
                    self.list = result.officialAccounts.data;
                    self.loading = false;
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            setStatus(id,status) {
                let self = this;
                let uri = "official-account/set-status/"+id+"/"+status;
                axios.get(uri).then(function (result) {
                    self.search();
                });
            },
            handleCurrentChange: function (val) {
                this.currentPage = val;
                this.search();
            },
            indexMethod: function (index) {
                return index + 1;
            },
            getInfo() {
                let self = this;
                let uri = "category/"+self.categoryId;
                axios.get(uri).then(function(result){
                    self.categoryName = result.data.name;
                });
            },
            //查询分类
            async queryIndustry(keyword = '') {
                let self = this;
                let uri = "category/search/"+keyword;
                axios.get(uri).then(function (result) {
                    self.restaurants = result.list;
                });
            },
            async queryCompany(keyword = '') {
                let self = this;
                let uri = "company/search/"+keyword;
                axios.get(uri).then(function (result) {
                    self.companies = result.list;
                });
            },
            async queryCompanyAsync(queryString, cb) {

                await this.queryCompany(queryString);

                var restaurants = this.companies;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            async querySearchAsync(queryString, cb) {

                await this.queryIndustry(queryString);

                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleFormQuerySelect(item){
                if (item && this.form.categoryIds.indexOf(item.id) == -1) {
                    this.form.categoryTags.push(item);
                    this.form.categoryIds.push(item.id);
                }
                this.form.categoryName = '';
            },
            handleFormIndustryClose(tag){
                this.form.categoryTags.splice(this.form.categoryTags.indexOf(tag), 1);
                this.form.categoryIds.splice(this.form.categoryIds.indexOf(tag.id),1);
            },
            handleCompanySelect(item) {
                if (item && this.form.companyIds.indexOf(item.id) === -1) {
                    this.form.companyTags.push(item);
                    this.form.companyIds.push(item.id);
                }
                this.form.companyName = '';
            },
            handleCompanyClose(tag) {
                this.form.companyTags.splice(this.form.companyTags.indexOf(tag), 1);
                this.form.companyIds.splice(this.form.companyIds.indexOf(tag.id), 1);
            },
            addAccount(){
                let self = this;

                self.title = "添加公众号";

                self.form.categoryIds = [self.categoryId];
                //console.log(self.categoryName);
                self.form.categoryTags = [{'value':self.categoryName,'id':self.categoryId}];

                self.form.companyIds = [];
                self.form.companyTags = [];

                self.form.account = "";

                self.form.name = '';
                self.form.account = '';
                self.form.dayNumber = 1;
                self.form.firstNumber = 0;
                self.form.status = 1;
                self.id = '';

                self.dialogFormVisible = true;
            },
            openEdit(row) {
                let self = this;
                self.title = "修改公众号";

                this.form.categoryIds = row.categoryTags;
                this.form.categoryTags = row.categoryNames;
                this.form.companyIds = row.companyTags;
                this.form.companyTags = row.companies;
                self.form.name = row.name;
                self.form.account = row.account;
                self.form.dayNumber = row.dayNumber;
                self.form.firstNumber = row.firstNumber;
                self.form.status = row.status;
                self.id = row._id;
                self.dialogFormVisible = true;
            },
            submitData(status) {
                let self = this;
                let categoryIds = this.form.categoryIds;
                let companyIds = this.form.companyIds;
                let dayNumber = parseInt(this.form.dayNumber);
                let firstNumber = parseInt(this.form.firstNumber);

                if(!this.form.name){
                    self.$message.error('公众号名称不能为空！');
                    return;
                }
                if(!this.form.account){
                    self.$message.error('微信号不能为空！');
                    return;
                }
                /*if (categoryIds.length > 0 && companyIds.length) {
                    console.log(categoryIds, companyIds);
                    self.$message.error('不能同时选择分类和公司！');
                    return;
                }*/
                if (dayNumber <= 0) {
                    self.$message.error('提取当日推送文章数量必须大于0！');
                    return;
                }
                self.loading = true;
                let uri = "official-account/store";
                let data = {
                    name:self.form.name,
                    account:self.form.account,
                    companyIds: companyIds, categoryIds: categoryIds,
                    dayNumber:dayNumber,
                    status:status,
                    firstNumber:firstNumber
                };
                self.dialogFormVisible = false;
                if (!self.id) {
                    axios.post(uri, data).then(function (result) {
                        self.search();
                    }).finally(() => {
                        self.dialogFormVisible = false;
                    });
                }else {
                    uri = "official-account/" + self.id;
                    axios.put(uri, data).then(function (result) {
                        self.search();
                    }).catch(function (error) {
                        self.loading = false;
                    });
                }

            }
        },
        mounted() {
            this.queryIndustry();
            this.queryCompany();
            this.search();
            this.getInfo();
        },
        filters: {
            titleFormatter(title) {
                if (title.length >= 10) {
                    return title.substring(0, 10) + '...';
                }
                return title.length === 0 ? '--' : title;
            }
        }
    }
</script>

<style scoped>

</style>
